import {
  orderConfirmListOrderInfo,
  productCarOrderCreateOrder,
  toPayByPayType,
  payBillService,
  getOrderPointServer,
  getOrgDistributionWayServer,
  getUserAddressServer,
} from '@/services/orderConfirm';
import {
  orderListServer,
  confirmGetItemServer,
  orderCancleServer,
  orderDetailServer,
  getOrderCancelReasonServer,
  expressQueryServer,
  createTakeawayOrderServer,
  getOrderStatusServer,
  applyAfterServiceServer,
  applyRefundServer,
  cancelRefundServer,
  confirmGetItemApplyServer,
  adjustmentListServer,
  getAdjustmentDetailServer,
  selectActivityAmountServer,
  affirmActivityServer,
} from '@/services/order';
import Taro from '@tarojs/taro';
import { appid, appid_h5 } from '@/src/config';
import { dealPayloadParams } from './commonFunc';

export default {
  namespace: 'order',
  state: {
    // 收银台获取支付优惠活动
    affirmActivity: {},

    // cartOrderCache: {} // 确认订单后接口返回的下一步提交信息， 订单id，订单项id
    cartOrderCache: {
      paymentData: {
        orderIdList: [],
        orderItemIdList: [],
      },
      totalPrice: 0.0,
    },

    refreshOrderId: null,

    orderDetailRefreash: null,
    orderStatusHis: null,

    orgDistributionWay: null,

    addrEnableList: [],
    addrUnableList: [],

    productInfoForAfterSale: {},
    adjustmentBefore: {},
    adjustmentBeforeTip: false,
    applyResult: {},
    adjustmentDetail: {},

    adjustmentList: [],
    adjustmentListParams: {},
    adjustmentListPagination: {},
    adjustmentListFinished: false,

    payActivity: {},
  },
  effects: {
    // 收银台获取支付优惠活动
    *getAffirmActivity({ payload }, { call, put }) {
      yield put({
        type: 'setAffirmActivity',
        payload: {},
      });

      const res = yield call(affirmActivityServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }

      yield put({
        type: 'setAffirmActivity',
        payload: res.content,
      });

      return res.content;
    },

    // 购物车选择商品后，获取选择商品的确认订单信息
    *getOrderConfirmInfo({ payload, noToast }, { call }) {
      const res = yield call(orderConfirmListOrderInfo, payload, noToast);
      const { code, content = {} } = res;
      if (code === '1') {
        return content;
      } else {
        const e = new Error(res.message);
        e.extra = res;
        return Promise.reject(e);
      }
    },
    // 购物车确认订单后，创建订单
    *createCartOrder({ payload, noToast }, { call, put }) {
      const { totalPrice } = payload;
      const res = yield call(productCarOrderCreateOrder, payload, noToast);
      const { code, content = {} } = res;
      if (code === '1') {
        yield put({
          type: 'setCartOrderCache',
          payload: {
            paymentData: content,
            totalPrice,
          },
        });

        // 重新获取购物车数量
        yield put({ type: 'productList/getCarNum', payload: {} });

        // 状态的异常值 1有某个商品无库存 2券/积分/礼品卡状态异常
        if (content?.exceptionType) {
          const e = new Error();
          e.extra = res;
          return Promise.reject(e);
        }

        return content;
      } else {
        const e = new Error(res.message);
        e.extra = res;
        return Promise.reject(e);
      }
    },

    // 购物车确认订单后，创建订单
    *toPayByPayType({ payload }, { call }) {
      let payAppId = Taro.$isH5 ? appid_h5 : appid;
      const res = yield call(toPayByPayType, { ...payload, payAppId });
      const { code, content = {}, message = '' } = res;
      if (code === '1') {
        return content;
      } else if (code === '0') {
        return { message };
      } else {
        // message.error(res.message);
        return Promise.reject();
      }
    },

    // 买单
    *payBill({ payload }, { call }) {
      const res = yield call(payBillService, payload);
      const { code, content = {} } = res;
      if (code === '1') {
        return content;
      } else {
        return Promise.reject();
      }
    },

    //订单列表
    *orderListModel({ payload }, { call }) {
      const res = yield call(orderListServer, payload);
      if (res.code === '1') {
        return res.content;
      }
    },

    //获取取消订单的原因
    *getOrderCancelReasonModel({ payload }, { call }) {
      const res = yield call(getOrderCancelReasonServer, payload);
      if (res.code === '1') {
        return res.content.orderCancelReasonList;
      }
    },

    //取消订单
    *orderCancleModel({ payload }, { call }) {
      const res = yield call(orderCancleServer, payload);
      if (res.code === '1') {
        Taro.showToast({
          title: '取消订单成功',
          icon: 'success',
          duration: 1500,
        });
      }
    },

    //订单详情
    *orderDetailModel({ payload }, { call }) {
      const res = yield call(orderDetailServer, payload.orderId);
      if (res.code === '1') {
        return res.content;
      }
    },

    //获取订单详情用来刷新订单列表的数据
    *orderDetailRefreashModel({ payload }, { call, put }) {
      const res = yield call(orderDetailServer, payload.orderId);
      if (res.code === '1') {
        let {
          created,
          distributeType,
          status,
          storeId,
          totalPayment,
          type,
          id,
          storeName,
          items = [],
        } = res.content;
        let number = 0;
        items.length > 0 &&
          items.map((product) => {
            number += Number(product.quantity);
          });
        yield put({
          type: 'setOrderDetailRefreash',
          payload: {
            created,
            distributeType,
            status,
            storeId,
            totalPayment,
            type,
            number,
            orderId: id,
            orgName: storeName,
            products: [...items],
          },
        });
      } else {
        Taro.showToast({
          title: '获取订单信息失败',
          duration: 1500,
          icon: 'none',
        });
      }
    },

    //确认收货
    *confirmGetItemModel({ payload }, { call }) {
      const res = yield call(confirmGetItemServer, payload);
      if (res.code === '1') {
        Taro.showToast({
          title: '确认收货成功',
          icon: 'success',
          duration: 1500,
        });
      } else {
        Taro.showToast({
          title: res.message,
          duration: 1500,
          icon: 'none',
        });
      }
    },

    //订单历史状态，用于物流信息页
    *getOrderStatusModel({ payload }, { call, put }) {
      const res = yield call(getOrderStatusServer, payload.orderId);
      if (res.code === '1') {
        yield put({
          type: 'setOrderStatusHis',
          payload: [...res.content],
        });
      } else {
        Taro.showToast({
          title: '获取订单状态失败',
          duration: 1500,
          icon: 'none',
        });
      }
    },

    //查询物流信息
    *expressQueryModel({ payload }, { call }) {
      const res = yield call(expressQueryServer, payload);
      if (res.code === '1') {
        return res.content;
      } else {
        return { expressQueryResult: '{}' };
      }
    },

    // 外卖订单提交
    *createTakeawayOrder({ payload }, { call, put }) {
      const res = yield call(createTakeawayOrderServer, payload);

      const { code, content } = res;
      if (code === '1') {
        yield put({
          type: 'setCartOrderCache',
          payload: {
            paymentData: content,
            totalPrice: payload.totalPrice,
          },
        });

        // 状态的异常值 1有某个商品无库存 2券/积分/礼品卡状态异常
        if (content?.exceptionType) {
          const e = new Error();
          e.extra = res;
          return Promise.reject(e);
        }

        return content;
      } else {
        const e = new Error(res.message);
        e.extra = res;
        return Promise.reject(e);
      }
    },

    // 获取订单可用积分
    *getOrderPoint({ payload }, { call, put }) {
      const { code, content } = yield call(getOrderPointServer, payload);

      if (code === '1') {
        yield put({
          type: 'setOrderPoint',
          payload: content,
        });
      } else {
        yield put({
          type: 'setOrderPoint',
          payload: undefined,
        });
      }
    },

    // 获取店铺支持的配送方式
    *getOrgDistributionWay({ payload }, { call, put }) {
      const res = yield call(getOrgDistributionWayServer, payload);

      const { code, content } = res;
      if (code === '1') {
        let { distributionWayList = [] } = content;
        let index = distributionWayList.findIndex((el) => el == '2');
        if (index !== -1 && index !== 0) {
          distributionWayList.splice(index, 1);
          distributionWayList.unshift('2');
        }
        yield put({
          type: 'setOrgDistributionWay',
          payload: {
            distributionWayList: [...distributionWayList],
          },
        });
      } else {
        Taro.showToast({
          title: '获取店铺配送方式失败',
          duration: 1500,
          icon: 'none',
        });
      }
    },

    //查询用户配送地址，同城配送距离校验
    *getUserAddressWithDistanceCheck({ payload }, { call, put }) {
      const res = yield call(getUserAddressServer, payload);

      const { code, content } = res;
      if (code === '1') {
        let addrEnableList = [],
          addrUnableList = [];
        content &&
          content.length > 0 &&
          content.map((item) => {
            if (item.isValid == '1') {
              addrEnableList.push(item);
            } else {
              addrUnableList.push(item);
            }
          });
        yield put({
          type: 'setUserAddressChecked',
          payload: {
            addrEnableList: [...addrEnableList],
            addrUnableList: [...addrUnableList],
          },
        });
      } else {
        Taro.showToast({
          title: '获取用户配送方式失败',
          duration: 1500,
          icon: 'none',
        });
      }
    },

    //发起售后
    *applyAfterService({ payload }, { call, put }) {
      const res = yield call(applyAfterServiceServer, payload);
      if (res.code === '1') {
        yield put({
          type: 'setAdjustmentBefore',
          payload: { ...res.content },
        });
      } else if (res.code === '0' && res.message == '只有待接单订单可以申请退款') {
        yield put({
          type: 'setAdjustmentBeforeTip',
          payload: true,
        });
      } else {
        Taro.showToast({
          title: res?.message || '请稍后再试',
          duration: 2500,
          icon: 'none',
        });
      }
    },

    //申请售后
    *applyRefund({ payload }, { call, put }) {
      const res = yield call(applyRefundServer, payload);
      if (res.code === '1') {
        yield put({
          type: 'setApplyResult',
          payload: { ...res.content },
        });
        Taro.redirectTo({
          url: '/orderSubPack/afterSale/applyResult/index',
        });
      } else if (res.code === '0' && res.message == '只有待接单订单可以申请退款') {
        yield put({
          type: 'setAdjustmentBeforeTip',
          payload: true,
        });
      } else {
        Taro.showToast({
          title: res?.message || '请稍后再试',
          duration: 2500,
          icon: 'none',
        });
      }
    },

    //撤销售后
    *applyAfterServiceServer({ payload }, { call }) {
      const res = yield call(cancelRefundServer, payload.id);
      if (res.code === '1') {
        Taro.showToast({
          title: '撤销售后成功',
          duration: 1500,
          icon: 'none',
        });
      } else {
        Taro.showToast({
          title: '撤销售后失败',
          duration: 1500,
          icon: 'none',
        });
      }
    },

    //售后换货时确认收货
    *confirmGetItem({ payload }, { call }) {
      const res = yield call(confirmGetItemApplyServer, payload.id);
      if (res.code === '1') {
        Taro.showToast({
          title: '确认收货成功',
          duration: 1500,
          icon: 'none',
        });
      } else {
        Taro.showToast({
          title: res.message,
          duration: 1500,
          icon: 'none',
        });
      }
    },

    //售后列表
    *adjustmentList({ payload }, { select, call, put }) {
      const params = yield select(({ order }) => order.adjustmentListParams);
      const curIsFinished = yield select(({ order }) => order.adjustmentListFinished);

      const isAlreadyFinished = dealPayloadParams(payload, params, curIsFinished);
      if (isAlreadyFinished) {
        return;
      }

      if (payload.page === 1) {
        yield put({
          type: 'setAdjustmentList',
          payload: {
            adjustmentList: [],
            adjustmentListFinished: false,
          },
        });
      }

      const res = yield call(adjustmentListServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1500,
          icon: 'none',
        });
        return Promise.reject();
      }

      const { list, pagination } = res.content;
      let dataList = [];
      if (payload.page != 1) {
        const oldList = yield select(({ order }) => order.adjustmentList);
        dataList = [...oldList, ...list];
      } else {
        dataList = [...list];
      }
      let isFinished = false;
      if (list.length < payload.pageSize) {
        isFinished = true;
      }
      yield put({
        type: 'setAdjustmentList',
        payload: {
          adjustmentList: dataList,
          adjustmentListPagination: { ...pagination },
          adjustmentListParams: { ...payload },
          adjustmentListFinished: isFinished,
        },
      });
    },

    //售后详情
    *getAdjustmentDetailModel({ payload }, { call, put }) {
      const res = yield call(getAdjustmentDetailServer, payload.id);
      if (res.code === '1') {
        yield put({
          type: 'setAdjustmentDetail',
          payload: { ...res.content },
        });
      } else {
        Taro.showToast({
          title: '获取售后详情失败',
          duration: 1500,
          icon: 'none',
        });
      }
    },

    //获取支付优惠活动
    *selectActivityAmount({ payload }, { call, put }) {
      const res = yield call(selectActivityAmountServer, payload);
      if (res.code === '1') {
        yield put({
          type: 'setPayActivity',
          payload: { ...res.content },
        });
      } else {
        Taro.showToast({
          title: '获取支付优惠活动失败',
          duration: 1500,
          icon: 'none',
        });
      }
    },
  },
  reducers: {
    // 收银台获取支付优惠活动
    setAffirmActivity(state, { payload }) {
      return {
        ...state,
        affirmActivity: payload,
      };
    },

    setCartOrderCache(state, { payload }) {
      return {
        ...state,
        cartOrderCache: payload,
      };
    },

    setOrderDetailRefreash(state, { payload }) {
      return {
        ...state,
        orderDetailRefreash: payload,
      };
    },

    // 清空订单可用积分
    resetOrderPoint(state, {}) {
      return {
        ...state,
        point: undefined,
      };
    },
    // 设置订单可用积分
    setOrderPoint(state, { payload }) {
      return {
        ...state,
        point: payload,
      };
    },

    // 设置需要刷新的orderId
    setRefreshOrderId(state, { payload }) {
      return {
        ...state,
        refreshOrderId: payload,
      };
    },

    setOrderStatusHis(state, { payload }) {
      return {
        ...state,
        orderStatusHis: payload,
      };
    },

    setOrgDistributionWay(state, { payload }) {
      const { distributionWayList } = payload;
      return {
        ...state,
        orgDistributionWay: distributionWayList,
      };
    },

    setUserAddressChecked(state, { payload }) {
      const { addrEnableList, addrUnableList } = payload;
      return {
        ...state,
        addrEnableList,
        addrUnableList,
      };
    },

    setProductInfoForAfterSale(state, { payload }) {
      return {
        ...state,
        productInfoForAfterSale: payload,
      };
    },

    setAdjustmentBefore(state, { payload }) {
      return {
        ...state,
        adjustmentBefore: payload,
      };
    },

    setAdjustmentBeforeTip(state, { payload }) {
      return {
        ...state,
        adjustmentBeforeTip: payload,
      };
    },

    setApplyResult(state, { payload }) {
      return {
        ...state,
        applyResult: payload,
      };
    },

    setAdjustmentList(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    setAdjustmentDetail(state, { payload }) {
      return {
        ...state,
        adjustmentDetail: payload,
      };
    },

    setPayActivity(state, { payload }) {
      return {
        ...state,
        payActivity: { ...payload },
      };
    },

    saveOrderDetail(state, { payload }) {
      return {
        ...state,
        orderDetail: { ...payload },
      };
    },
  },
};
